﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Windows.Forms;

namespace umsoftU3.Common
{
    /// <summary>
    /// Html to PDF
    /// </summary>
    public class BirthPdf
    {
        private System.Drawing.Bitmap bitmap;
        private string url;
        private int w = 1024, h = 800;
        public void setBitmap()
        {
            using (WebBrowser wb = new WebBrowser())
            {
                wb.Width = w;
                wb.Height = h;
                wb.ScrollBarsEnabled = false;
                wb.Navigate(url);
                //确保页面被解析完全
                while (wb.ReadyState != WebBrowserReadyState.Complete)
                {
                    System.Windows.Forms.Application.DoEvents();
                }
                bitmap = new System.Drawing.Bitmap(w, h);
                wb.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, w, h));
                wb.Dispose();
            }
        }
        public  Stream CreatPdf(string strBitMap,string outPdf,string strUrl)
        {
            iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A3, 36, 36, 36, 36);//左右上下
            MemoryStream ms = new MemoryStream();
            try
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, ms);
                writer.CloseStream = false;
                doc.Open();
                url = strUrl;
                Thread thread = new Thread(new ThreadStart(setBitmap));
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                while (thread.IsAlive)
                    Thread.Sleep(100);
                bitmap.Save(strBitMap);

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);
                img.ScalePercent(75);//560 630
                doc.Add(img);
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
            finally
            {
                doc.Close();
                using (FileStream fs = new FileStream(outPdf, FileMode.Create))
                {
                    ms.Position = 0;
                    byte[] bit = new byte[ms.Length];
                    ms.Read(bit, 0, (int)ms.Length);
                    fs.Write(bit, 0, bit.Length);
                }
            }
            return ms;
        }
    }
}